'use strict';
let request = require('request');
let queryString = require('querystring');
let co = require('co');
let debug = require('./src/common/debug')('debug');

let hex_md5 = require('./src/libs/md5');
let cookieHelper = require('./src/common/cookie-helper');

let vcode = new Date().getTime();
let userName = 'aiyikang123';
let password = hex_md5('123456');

let authBody = {
  'userName':userName,
  'passWord':password    
};
let cookies = [];
debug(`authBody.passWord: ${authBody.passWord}; vcode: ${vcode}`);

var options = {
  'url': `http://cloud.aek56.com/ajax/?a=ajax_login&callback=jQuery111005857525110379616_1483005866115&t=${Math.random()}&userName=${authBody.userName}&passWord=${authBody.passWord}&vcode=${vcode}`,
  'method': 'GET',
  'body': queryString.stringify(authBody),
  'headers': {
    'Content-type': 'application/x-www-form-urlencoded',
    'Content-length': queryString.stringify(authBody).length,
  },
  //'jar': true  
};

function callback(error, response, body) {
  if(error) debug(`error: ${error.message, error.stack}`);
  if (!error && response.statusCode == 200) {
  
    cookieHelper.addResCookieToCookies(response, cookies);
    debug('response.headers[\'set-cookie\']'+cookies['PHPSESSID']);
    debug(`response from login: ${JSON.stringify(response,null,' ')}`);

    let getOption = {
      'url':`http://cloud.aek56.com/ajax/?a=menu&t=${Math.random()}`,
      'method': 'POST',
      'form': {
        'act':'menu',
        'parentId':82
      },
      'headers': {
        'Cookie': cookieHelper.cookiesToString(cookies)         
      },  
    };
        
    request(getOption,function (error, response, body){
      if(error) console.log(`error: ${error.message, error.stack}`);
      if (!error && response.statusCode == 200) {
        debug(`responose: ${JSON.stringify(response,null,' ')}`);
        debug(`json body: ${JSON.stringify(body,null,' ')}`);
        debug('You\'ve made it!');
      }
    });

  }
}

request(options, callback);


